import { Input } from 'antd';
import { type ChangeEvent, useEffect, useState } from 'react';
import { degree2DMS, gps2Degree } from '../weapon';
import styles from './nwse.module.less';

type NWSEProps = {
  className?: string;
  maximum?: number;
  minimum?: number;
  value?: number | null;
  units?: [string, string];
  onChange?: (val: number | null) => void;
};

const NWSE = (props: NWSEProps) => {
  const { className, maximum, minimum, value, units, onChange } = props;

  const [text, setText] = useState<string | null>('');

  useEffect(() => {
    if (value !== null && value !== undefined && units) {
      const dir = value < 0 ? units[0] : units[1];
      setText(degree2DMS(value.toFixed(6), dir));
    } else {
      setText('');
    }
  }, [value]);

  const onTextChange = (e: ChangeEvent<HTMLInputElement>) => {
    const txt = e.target.value;
    setText(txt);
    const [dir, val] = gps2Degree(txt);
    const idx = units?.indexOf(dir?.toString() || '');
    let num = (idx === 0 ? -1 : 1) * (val as number);
    if (maximum !== undefined) {
      if (num > maximum) num = maximum;
    }
    if (minimum !== undefined) {
      if (num < minimum) num = minimum;
    }
    onChange?.(num);
  };

  return (
    <div className={`${styles.root} ${className}`}>
      <Input
        style={{ width: 264, marginRight: 5 }}
        placeholder="N DD°MM′SS″"
        value={text || ''}
        onChange={onTextChange}
      />
    </div>
  );
};

export default NWSE;
